package main

import (
	"fmt"
	"os"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
)

// FileMate 文件元信息
type FileMate struct {
	gorm.Model
	Name       string
	UploadTime string
}

func (f FileMate) String() string {
	return "上传时间：" + f.UploadTime + "  文件名：" + f.Name
}

func connectDB() (db *gorm.DB, err error) {
	viper.SetConfigName("config") //设置配置文件的名字
	viper.AddConfigPath(".")      //添加配置文件所在的路径
	viper.SetConfigType("json")   //设置配置文件类型，可选
	err = viper.ReadInConfig()
	if err != nil {
		fmt.Printf("config file error: %s\n", err)
		os.Exit(1)
	}
	s := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
		viper.Get("mysql.username"), viper.Get("mysql.password"),
		viper.Get("mysql.url"), viper.Get("mysql.database"))
	db, err = gorm.Open("mysql", s)
	return
}

// UpdateFileMate 更新文件元信息
func UpdateFileMate(name string, time string) {

	// db, err := gorm.Open("mysql", "root:xjk0218@/test?charset=utf8&parseTime=True&loc=Local")
	db, err := connectDB()
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()

	// Migrate the schema
	db.AutoMigrate(&FileMate{})

	// 创建
	db.Create(&FileMate{Name: name, UploadTime: time})
}

// GetFilesInfo 获得所有文件信息
func GetFilesInfo() []string {
	// db, err := gorm.Open("mysql", "root:xjk0218@/test?charset=utf8&parseTime=True&loc=Local")
	db, err := connectDB()
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()

	res := make([]string, 0)
	rows, err := db.Model(&FileMate{}).Select("name,upload_time").Rows()
	if err != nil {
		fmt.Println(err)
		return res
	}
	for rows.Next() {
		var fileMate FileMate
		// ScanRows 扫描一行记录到 res
		db.ScanRows(rows, &fileMate)
		res = append(res, fileMate.String())
	}
	//fmt.Print(res)
	return res
}
